<template>
  <div class="designer-form flex flex-col justify-center items-center">
    <el-form
      ref="baseFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="120px"
      :size="formSize"
      status-icon
    >
      <!-- <el-form-item label="主体类型" prop="subjectType" required label-position="right">
        <el-select
          v-model="ruleForm.subjectType"
          placeholder="请选择"
          clearable
          disabled
          @change="handleChangeMode"
        >
          <el-option
            v-for="dict in subjectTypeList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="所在商圈/商场" prop="mallName" required>
        <div class="mall-select-wrapper">
          <template v-if="activeMallMode === 'SELECT'">
            <el-select
              v-model="ruleForm.mallNameId"
              placeholder="请选择"
              clearable
              class="mall-select"
              @change="
                () => {
                  ruleForm.mallName = mallList.find(
                    (item) => item.id === ruleForm.mallNameId
                  )?.mallName;
                }
              "
            >
              <el-option
                v-for="item in mallList"
                :key="item.id"
                :label="item.mallName"
                :value="item.id"
              />
            </el-select>
          </template>
          <template v-else>
            <el-input v-model="ruleForm.mallName" class="mall-select" />
          </template>
          <el-button type="primary" link @click="changeMallMode">{{ mallChangeTitle }}</el-button>
        </div>
      </el-form-item>

      <el-form-item label="身份证图片" class="id-card-upload" required>
        <el-text type="info" size="small">
          1. 请上传中国大陆地区身份证图片，保证图片清晰，身份证大小与图片大小一致
        </el-text>
        <el-text type="info" size="small">2. 请上传身份证正反两面图片</el-text>
      </el-form-item>
      <el-row :gutter="20" class="upload-row">
        <el-col :span="12">
          <el-form-item label="正面" prop="idCardFrontFile" class="upload-item">
            <MultiImageUpload
              v-model="ruleForm.idCardFrontFile"
              :limit="1"
              :isSmallUpload="true"
              @uploadSuccess="handleCardFrontFile"
            />
            <!-- <ImageUpload
              v-model="ruleForm.idCardFrontFile"
              limit="1"
              @update:modelValue="handleCardFrontFile"
            /> -->
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="反面" prop="idCardBackFile" class="upload-item">
            <!-- <ImageUpload
              v-model="ruleForm.idCardBackFile"
              limit="1"
              @update:modelValue="handleCardBackFile"
            /> -->
            <MultiImageUpload
              v-model="ruleForm.idCardBackFile"
              :limit="1"
              :isSmallUpload="true"
              @uploadSuccess="handleCardBackFile"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="form-section">
        <el-form-item label="身份证号码" prop="idNumber" required>
          <el-input v-model="ruleForm.idNumber" placeholder="请输入身份证号码" />
        </el-form-item>
        <el-form-item label="身份证有效期限" required prop="idCardValidity">
          <el-date-picker
            v-model="ruleForm.idCardValidity"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYYMMDD"
          />
        </el-form-item>
      </div>

      <div class="form-section">
        <el-form-item label="姓名" prop="businessContactName" required>
          <el-input v-model="ruleForm.businessContactName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="businessContactPhone" required>
          <el-input v-model="ruleForm.businessContactPhone" placeholder="请输入手机号" />
        </el-form-item>
      </div>

      <div class="form-actions">
        <el-button class="big-button" type="primary" @click="submitForm">提交</el-button>
        <!-- <el-button @click="resetForm(baseFormRef)">重置</el-button> -->
      </div>
    </el-form>
  </div>
</template>

<script setup>
// 请求
import { getMallList } from "@/api/settleMiddle/mall";
import {
  addMerchantEmployee,
  editMerchantEmployee,
  getIdCardFaceInfo,
  getIdCardBackInfo,
} from "@/api/settleMiddle/index";
// 组件
import ImageUpload from "@/components/ImageUpload/index.vue";
import { validateIdCard, validatePhone } from "@/utils/formvalidate";
const props = defineProps({
  subjectTypeList: {
    type: Array,
    default: () => [],
  },
  defaultForm: {
    type: Object,
    default: () => {},
  },
});
const formSize = ref("default");
const proxy = getCurrentInstance();
const emit = defineEmits(["submitSuccess"]);
/***
 * 表单校验管理
 *
 */

const ruleForm = reactive({
  subjectType: props.subjectTypeList[0].value,
  mallNameId: "",
  mallName: "",
  businessContactName: "",
  businessContactPhone: "",
  idNumber: "",
  idCardValidity: "",
  idCardFrontFile: [],
  idCardBackFile: [],
});
// 上传图片统一处理
const handleCardFrontFile = () => {
  identifyFaceCard();

  // console.log(businessLicenseFile, 'businessLicenseFile')
  //topImage.value = value[0]
};
const handleCardBackFile = () => {
  identifyBackCard();
};

const rules = reactive({
  subjectType: [{ required: true, message: "请选择主体类型", trigger: "blur" }],
  mallName: [{ required: true, message: "请选择或者填写商圈/商场", trigger: "blur" }],
  businessContactName: [{ required: true, message: "请输入业务代表人姓名", trigger: "blur" }],
  businessContactPhone: [
    { required: true, message: "请输入业务代表人手机号", trigger: "blur" },
    { validator: validatePhone, trigger: "blur" },
  ],
  idNumber: [
    { required: true, message: "请输入法人代表身份证号码", trigger: "blur" },
    { validator: validateIdCard, trigger: "blur" },
  ],
  idCardValidity: [{ required: true, message: "请选择身份证有效期限", trigger: "blur" }],
  idCardFrontFile: [{ required: true, message: "请上传法定代表人身份证正面图片", trigger: "blur" }],
  idCardBackFile: [{ required: true, message: "请上传法定代表人身份证反面图片", trigger: "blur" }],
});

/**
 *  所在商圈/商场 处理
 *
 */
const mallList = ref([]);
// SELECT 和 INPUT 模式
const activeMallMode = ref("SELECT");
const mallChangeTitle = ref("手动填写");
const changeMallMode = () => {
  // 清空商圈选中的值
  ruleForm.mallNameId = "";
  ruleForm.mallName = "";
  activeMallMode.value = activeMallMode.value === "SELECT" ? "INPUT" : "SELECT";
  mallChangeTitle.value = activeMallMode.value === "SELECT" ? "手动填写" : "选择商圈";
};
async function funcGetMallList() {
  try {
    const data = await getMallList();
    mallList.value = data.data;
  } catch (err) {
    console.log(err);
  }
}

const submitForm = async () => {
  let formEl = proxy?.refs?.baseFormRef;
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      handleAddMerchantEmployee({
        ...ruleForm,
        idCardValidity:
          ruleForm.idCardValidity && ruleForm.idCardValidity.length > 0
            ? ruleForm.idCardValidity.join(",")
            : "",
        idCardBackFile: JSON.stringify(ruleForm.idCardBackFile),
        idCardFrontFile: JSON.stringify(ruleForm.idCardFrontFile),
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

// const resetForm = (formEl) => {
//   if (!formEl) return;
//   formEl.resetFields();
// };

const handleAddMerchantEmployee = async (params) => {
  try {
    props.defaultForm?.id
      ? await editMerchantEmployee({ ...params, id: props.defaultForm.id })
      : await addMerchantEmployee(params);
    emit("submitSuccess");
  } catch (err) {
    console.log(err);
  }
};
const handleChangeMode = () => {
  console.log("handleChangeMode");
};
const handleDefaultForm = () => {
  ruleForm.subjectType = props.defaultForm.subjectType;
  ruleForm.mallNameId = props.defaultForm.mallNameId;
  ruleForm.mallName = props.defaultForm.mallName;
  ruleForm.businessContactName = props.defaultForm.businessContactName;
  ruleForm.businessContactPhone = props.defaultForm.businessContactPhone;
  ruleForm.idNumber = props.defaultForm.idNumber;
  ruleForm.idCardValidity = props.defaultForm.idCardValidity.split(",");
  ruleForm.idCardFrontFile = JSON.parse(props.defaultForm.idCardFrontFile);
  ruleForm.idCardBackFile = JSON.parse(props.defaultForm.idCardBackFile);
};
/**
 * ocr 识别
 *
 *
 */
// 身份证正面
const identifyFaceCard = async () => {
  try {
    const data = await getIdCardFaceInfo({
      url: ruleForm?.idCardFrontFile[0]?.url,
    });
    ruleForm.legalRepresentative = data.data.name;
    ruleForm.idNumber = data.data.num;
  } catch (err) {
    console.log(err);
  }
};
// 身份证反面
const identifyBackCard = async () => {
  try {
    const data = await getIdCardBackInfo({
      url: ruleForm?.idCardBackFile[0]?.url,
    });
    ruleForm.idCardValidity = [data.data.startDate, data.data.endDate];
  } catch (err) {
    console.log(err);
  }
};
watchEffect(() => {
  if ("id" in props.defaultForm) {
    handleDefaultForm();
  }
});
onMounted(() => {
  funcGetMallList();
});
</script>

<style lang="scss" scoped>
.designer-form {
  max-width: 700px;
  margin: 0px auto;
  padding: 50px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

  .mall-select-wrapper {
    display: flex;
    align-items: center;
    gap: 12px;

    .mall-select {
      width: 300px;
    }
  }

  .id-card-upload {
    .upload-tips {
      display: flex;
      flex-direction: column;
      gap: 4px;
      margin-bottom: 16px;
      color: #909399;
      font-size: 12px;
    }

    .upload-row {
      margin-top: 16px;
    }

    .upload-item {
      margin-bottom: 0;
    }
  }

  .form-section {
    padding: 16px 0;

    &:last-child {
      border-bottom: none;
    }
  }

  .date-picker {
    width: 100%;
  }

  .form-actions {
    display: flex;
    justify-content: center;
    gap: 16px;
    margin-top: 32px;
    padding-top: 24px;
    border-top: 1px solid #ebeef5;
  }

  .big-button {
    width: 300px;
    height: 40px;
    margin: 20px auto;
  }
}
</style>
